#!/bin/bash

# 创建自签名开发证书用于本地开发
# 这个脚本会在系统钥匙串中创建一个 "Apple Development" 证书

echo "🔐 创建本地开发证书..."
echo ""
echo "⚠️  注意：这将创建一个自签名证书用于本地开发"
echo "   如果您有 Apple Developer 账号，建议使用 Xcode 自动管理签名"
echo ""
read -p "按 Enter 继续，或 Ctrl+C 取消..."

# 创建证书
security create-keychain -p "" flutter-dev.keychain || true
security set-keychain-settings -t 3600 -l ~/Library/Keychains/flutter-dev.keychain
security unlock-keychain -p "" ~/Library/Keychains/flutter-dev.keychain

# 生成自签名证书
cat > /tmp/cert.cfg <<EOF
[ req ]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no

[ req_distinguished_name ]
CN = Apple Development: Local Dev
O = Local Development
C = CN

[ v3_req ]
keyUsage = critical,digitalSignature
extendedKeyUsage = critical,codeSigning
basicConstraints = critical,CA:false
EOF

# 生成密钥和证书
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
    -keyout /tmp/dev-cert.key \
    -out /tmp/dev-cert.crt \
    -config /tmp/cert.cfg \
    2>/dev/null

# 转换为 p12 格式
openssl pkcs12 -export -out /tmp/dev-cert.p12 \
    -inkey /tmp/dev-cert.key \
    -in /tmp/dev-cert.crt \
    -passout pass:

# 导入到钥匙串
security import /tmp/dev-cert.p12 -k ~/Library/Keychains/flutter-dev.keychain -P "" -T /usr/bin/codesign

# 设置信任
security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/flutter-dev.keychain /tmp/dev-cert.crt

# 清理临时文件
rm -f /tmp/cert.cfg /tmp/dev-cert.key /tmp/dev-cert.crt /tmp/dev-cert.p12

echo ""
echo "✅ 证书创建完成！"
echo ""
echo "📋 查看证书："
security find-identity -v -p codesigning
echo ""
echo "💡 如果构建仍然失败，请运行："
echo "   security unlock-keychain ~/Library/Keychains/flutter-dev.keychain"

